<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Cache;

/**
 * 阅读任务用户执行数据库表
 * Class ArticleModel
 * @package app\common\model
 */
class ReadingTaskExecuteDatabase extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'reading_task_execute_database';


    /**
     * 判断某个任务下的数据库阅读任务是否完成
     * @param user_id 用户id
     * @param task_id 阅读任务id
     * @param database_id 数据库id
     */
    public function readingTaskDatabaseProgress($user_id, $task_id, $database_id)
    {
        $reading_task_database = $this->where('user_id', $user_id)->where('task_id', $task_id)->where('database_id', $database_id)->first();
        if ($reading_task_database && ($reading_task_database['progress'] == 100 || $reading_task_database['progress'] == '100.00' )) {
            return true;
        }
        //更新数据库阅读任务进度
        $readingTaskExecuteWorksModel = new ReadingTaskExecuteWorks();
        $competiteActivityWorksDatabaseModel = new CompetiteActivityWorksDatabase();
        $database_reading_number = $readingTaskExecuteWorksModel->readingWorksNumber($user_id, $task_id, $database_id);
        $database_works_number = $competiteActivityWorksDatabaseModel->databaseWorksNumber($database_id);
        if ($database_reading_number >= $database_works_number) {
            $progress = 100;
        } else {
            $progress = sprintf("%.2f", $database_works_number / $database_reading_number);
        }
        if ($reading_task_database) {
            $reading_task_database->progress = $progress;
            $reading_task_database->save();
        } else {
            $this->task_id = $task_id;
            $this->user_id = $user_id;
            $this->database_id = $database_id;
            $this->progress = $progress;
            $this->save();
        }
        return true;
    }
}
